<template>
  <a-row justify="center">
    <div style="width:  1000px">
      <a-spin :spinning="data.spinning" size="large">
        <a-row>
          <a-card hoverable style="width: 600px">
            <template #actions>
              <a-button @click="dowloadChange">
                <template #icon>
                  <DownloadOutlined/>
                </template>
                下载
              </a-button>
              <a-button @click="clearHandle">
                <template #icon>
                  <SyncOutlined/>
                </template>
                清空
              </a-button>
            </template>
            <a-card-meta title="">
              <template #description>
                <a-row justify="center">
                  <a-qrcode ref="qrcodeCanvasRef" :size="400" :value="data.showForm.weight"/>
                </a-row>
                <a-table :pagination="false" :scroll="{x:500,y:300}" :dataSource="data.lista" :columns="columns"/>
              </template>
            </a-card-meta>
          </a-card>
          <a-card hoverable style="width: 400px">

            <a-form :disabled="data.formStatus" :model="data.form" ref="formRef" :rules="rules">
              <a-form-item label="串口号" name="serialPort">
                <a-select v-model:value="data.form.serialPort">
                  <a-select-option v-for="it in data.listb" :key="it" :value="it"></a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="波特率" name="baudRate">
                <a-select v-model:value="data.form.baudRate">
                  <a-select-option :key="110" :value="100"></a-select-option>
                  <a-select-option :key="300" :value="300"></a-select-option>
                  <a-select-option :key="600" :value="600"></a-select-option>
                  <a-select-option :key="1200" :value="1200"></a-select-option>
                  <a-select-option :key="2400" :value="2400"></a-select-option>
                  <a-select-option :key="4800" :value="4800"></a-select-option>
                  <a-select-option :key="9600" :value="9600"></a-select-option>
                  <a-select-option :key="14400" :value="14400"></a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="校验位" name="checkBit">
                <a-select v-model:value="data.form.checkBit">
                  <a-select-option key="NONE" value="NONE"></a-select-option>
                  <a-select-option key="ODD" value="ODD"></a-select-option>
                  <a-select-option key="EVEN" value="EVEN"></a-select-option>
                  <a-select-option key="MARK" value="MARK"></a-select-option>
                  <a-select-option key="SPACE" value="SPACE"></a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="数据位" name="dataBit">
                <a-select v-model:value="data.form.dataBit">
                  <a-select-option key="5 bit" value="5 bit"></a-select-option>
                  <a-select-option key="6 bit" value="6 bit"></a-select-option>
                  <a-select-option key="7 bit" value="7 bit"></a-select-option>
                  <a-select-option key="8 bit" value="8 bit"></a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="停止位" name="stopBit">
                <a-select v-model:value="data.form.stopBit">
                  <a-select-option key="1 bit" value="1 bit"></a-select-option>
                  <a-select-option key="1.5 bit" value="1.5 bit"></a-select-option>
                  <a-select-option key="2 bit" value="2 bit"></a-select-option>
                </a-select>
              </a-form-item>
            </a-form>
            <template #actions>
              <a-button :disabled="data.connectStatus" @click="connectHandle" type="primary">连接</a-button>
              <a-button :disabled="!data.connectStatus" @click="breakHandle" type="primary" danger>断开</a-button>
            </template>
          </a-card>
        </a-row>
      </a-spin>
    </div>
  </a-row>
</template>

<script setup>

import {reactive, ref, onMounted} from "vue";
import request from "./util/request";
import {message, notification} from "ant-design-vue";

const qrcodeCanvasRef = ref();

const formRef = ref({})

const columns = ref([
      {
        title: '日期',
        dataIndex: 'localDate',
        key: 'localDate',
        align: 'center',
      },
      {
        title: '时间',
        dataIndex: 'localTime',
        key: 'localTime',
        align: 'center',
      },
      {
        title: '重量',
        dataIndex: 'weight',
        key: 'weight',
        align: 'center',
      },
      {
        title: '单位',
        dataIndex: 'unit',
        key: 'unit',
        align: 'center',
      },
    ]
);

const rules = {
  serialPort: [
    {
      required: true,
      message: '请选择串口名称',
    },
  ],
  baudRate: [
    {
      required: true,
      message: '请选择波特率',
    },
  ],
  checkBit: [
    {
      required: true,
      message: '请选择波校验位',
    },
  ],
  dataBit: [
    {
      required: true,
      message: '请选择数据位',
    },
  ],
  stopBit: [
    {
      required: true,
      message: '请选择停止位',
    },
  ],

};
const data = reactive({
  form: {
    serialPort: '',
    baudRate: 9600,
    checkBit: 'NONE',
    dataBit: '8 bit',
    stopBit: '1 bit'
  },
  showForm: {
    localDate: new Date().getUTCDate(),
    localTime: '',
    weight: '0.00',
    unit: 'g'
  },
  lista: [],
  listb: [],
  connectStatus: false,
  formStatus: false,
  spinning: false,

})

function pageInfo() {
  request.get(`/com/list`).then(res => {
    data.listb = res.data.data;
  })
}


onMounted(() => {
  pageInfo();
  initWebSocket()
})

function notify(msg) {
  notification.warn({
    message: '警告提示',
    description: msg,
    placement: 'topRight',
  })
}


function connectHandle() {
  data.spinning = true;
  formRef.value.validate().then(() => {
    request.get(`/com/excute?serialPort=${data.form.serialPort}`).then(res => {
      data.spinning = false;
      data.formStatus = true;
      data.connectStatus = true
      notify(`串口 {${data.form.serialPort}} 和服务器连接成功！`)
    }).catch(err => {
      data.spinning = false;
      notify(`串口 {${data.form.serialPort}} 和服务器连接失败！`)
    })
  }).catch(err => {
    data.spinning = false;
    data.formStatus = false
    notify("页面校验失败！")
  });
}

function breakHandle() {
  data.spinning = true;
  request.get(`/com/breakHandle?serialPort=${data.form.serialPort}`).then(res => {
    data.connectStatus = false
    data.spinning = false;
    data.formStatus = false;
    notify(`串口 {${data.form.serialPort}} 和服务器断开成功！`)
  }).catch(error => {
    data.spinning = false;
    notify(`串口 {${data.form.serialPort}} 和服务器断开失败！`)
  })
}


function initWebSocket() {
  const webSocket = new WebSocket(`ws://localhost:10000/websocket/1`)


  webSocket.onopen = (ev) => {
    notify("双向通信开启成功！")
  }
  webSocket.onerror = (ev) => {
    notify("双向通信开启失败！")
  }
  webSocket.onmessage = (res) => {
    data.showForm = JSON.parse(res.data)
    data.lista.unshift(data.showForm)
    notify("服务器发送数据！")
  }
  webSocket.onclose = (ev) => {
    notify("双向通信关闭成功！")
  }


}


function dowloadChange() {
  const url = qrcodeCanvasRef.value.toDataURL();
  const a = document.createElement('a');
  let data = new Date()
  a.download = `${data.getFullYear()}${data.getMonth()}${data.getDate()}${data.getHours()}${data.getMinutes()}${data.getSeconds()}.png`;
  a.href = url;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}


function clearHandle() {
  data.lista = []
}


</script>
<style>


.ant-form-item {
  margin-bottom: 2px;

  .ant-row {
    margin-bottom: 2px;
  }
}

.ant-table-cell {
  padding-bottom: 2px !important;
  padding-top: 2px !important;
}


</style>